package udp_tcp;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class UDPServer {
    public static void main(String[] args) {
        // 指定服务器监听的端口
        int port = 9876;

        try (DatagramSocket serverSocket = new DatagramSocket(port)) {
            System.out.println("UDP服务器已启动，等待客户端连接...");

            while (true) {
                // 创建接收数据的缓冲区
                byte[] receiveData = new byte[1024];

                // 创建接收数据包
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

                // 接收数据
                serverSocket.receive(receivePacket);

                // 解析接收到的数据
                String message = new String(receivePacket.getData(), 0, receivePacket.getLength());
                InetAddress clientAddress = receivePacket.getAddress();
                int clientPort = receivePacket.getPort();

                System.out.println("收到来自 " + clientAddress.getHostAddress() + ":" + clientPort + " 的消息: " + message);

                // 准备响应数据
                String response = "服务器已收到你的消息: " + message;
                byte[] sendData = response.getBytes();

                // 创建并发送响应数据包
                DatagramPacket sendPacket = new DatagramPacket(
                        sendData,
                        sendData.length,
                        clientAddress,
                        clientPort
                );
                serverSocket.send(sendPacket);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}